package com.stone.design.mode.state.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;

/**
 * 订单状态监听器，一旦状态发生变化，在触发对应的事件处理（观察者模式）
 *
 * @author wenpan 2022/06/18 17:30
 */
@Slf4j
@Component("orderStateListener")
// 绑定监听的状态机
@WithStateMachine(name = "orderStateMachine")
public class OrderStateListenerImpl {

    /**
     * 状态转换回调方法
     */
    @OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER")
    public boolean payTransition(Message message) {
        // 获取消息，消息从哪里来？？？
        Order order = (Order) message.getHeaders().get("order");
        order.setStatus(OrderStatus.WAIT_DELIVER);
        log.info("支付，状态机反馈信息：" + message.getHeaders().toString());
        return true;
    }

    /**
     * 状态转换回调方法
     */
    @OnTransition(source = "WAIT_DELIVER", target = "WAIT_RECEIVE")
    public boolean deliverTransition(Message message) {
        // 获取消息，消息从哪里来？？？
        Order order = (Order) message.getHeaders().get("order");
        order.setStatus(OrderStatus.WAIT_RECEIVE);
        log.info("支付，状态机反馈信息：" + message.getHeaders().toString());
        return true;
    }

    /**
     * 状态转换回调方法
     */
    @OnTransition(source = "WAIT_RECEIVE", target = "FINISH")
    public boolean receiveTransition(Message message) {
        // 获取消息，消息从哪里来？？？
        Order order = (Order) message.getHeaders().get("order");
        order.setStatus(OrderStatus.FINISH);
        log.info("支付，状态机反馈信息：" + message.getHeaders().toString());
        return true;
    }
}
